<?php


namespace PKApp\Site\Classes;


use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\MatchHelper;
use PKFrame\Service;

class SiteService extends Service
{
    protected $moduleName = 'Site';

    protected function db(): SiteDataBase
    {
        !empty(self::$db) ?: self::$db = new SiteDataBase();
        return self::$db;
    }

    public function GetList($viewParams = [], $viewField = '*')
    {
        if (Arrays::Is($viewParams)) {
            $this->db()->Where($viewParams);
        }
        return $this->db()->Select($viewField)->ToList();
    }

    public function GetCount(): int
    {
        return $this->db()->Count();
    }

    public function GetEntity($viewParams = [], $viewField = '*'): ?array
    {
        return $this->db()->GetSite($viewParams, $viewField);
    }

    public function interface_getEntityById($id, $viewField = '*'): array
    {
        $siteEntity = $this->getEntityById($id, 'Site_IdEmpty', 'Site_Empty', $viewField);
        if (!in_array(request()->controller(), ['AdminGetSite']) && is_array($siteEntity) && array_key_exists('Site_Domain', $siteEntity)) {
            MatchHelper::checkUrlOfScheme($siteEntity['Site_Domain']) ?: $this->noticeByJson('Site_Domain_Error', 'site');
        }
        return $siteEntity;
    }

    public function GetDomain(int $id_site)
    {
        $siteEntity = $this->interface_getEntityById($id_site, ['Site_Domain']);
        return $siteEntity['Site_Domain'];
    }

}